package com.jasonzhou.onetomanycontrol.dialog

import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentManager
import com.jasonzhou.onetomanycontrol.R
import com.jasonzhou.onetomanycontrol.databinding.DialogTipsBinding

class TipsDialog : DialogFragment(), View.OnClickListener {
    lateinit var binding: DialogTipsBinding

    val isShowing: Boolean
        get() = dialog != null && dialog!!.isShowing

    var listener: ((Int) -> Unit)? = null

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        dialog?.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        binding = DialogTipsBinding.inflate(inflater)
        initView()
        dialog?.window?.attributes?.windowAnimations = R.style.dialogAnim
        return binding.root
    }

    override fun onResume() {
        super.onResume()
        val m = requireActivity().windowManager
        val d = m.defaultDisplay
        val params = binding.root.layoutParams
        params.width = (d.width * 0.7f).toInt()
        params.height = WindowManager.LayoutParams.WRAP_CONTENT
        binding.dialogRgbLayout.layoutParams = params
        dialog?.window?.setLayout(params.width, WindowManager.LayoutParams.WRAP_CONTENT)

        //设置出现的位置
        val lp = dialog!!.window!!.attributes
        //        lp.y = -(int) (d.getHeight() * 0.12f);
        lp.gravity = Gravity.CENTER
        dialog?.window?.attributes = lp

        isCancelable = false
        dialog?.setCanceledOnTouchOutside(false)
    }

    private fun initView() {
        binding.dialogRgbConfirm.setOnClickListener(this)
        binding.dialogRgbCancel.setOnClickListener(this)

        binding.privacyContent.text = mContent
    }

    fun show(manager: FragmentManager, tag: String?, content: String) {
        mContent = content;
        super.show(manager, tag)
    }

    private var mContent: String = ""

    override fun onClick(v: View) {
        when (v.id) {
            R.id.dialog_rgb_confirm -> {
                listener?.invoke(0)
                dismiss()
            }

            R.id.dialog_rgb_cancel -> {
                listener?.invoke(1)
                dismiss()
            }
        }
    }
}
